package com.heima.item.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.item.pojo.Item;
import com.heima.item.pojo.ItemStock;
import com.heima.item.service.IItemService;
import com.heima.item.service.IItemStockService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Xiao
 * @version 1.0
 * @description Redis初始化预热处理
 * @date 2021/11/18
 */
@Component
public class RedisHandler implements InitializingBean {
    /**
     * InitializingBean接口的afterPropertiesSet()方法
     * 会在对象被Spring创建并且成员变量全部注入后执行。
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IItemService itemService;
    @Autowired
    IItemStockService stockService;
    /**
     * MAPPER.writeValueAsString(Object o) --> JSON序列化方法
     */
    @Autowired
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * Redis初始化缓存预热
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //从数据库查询信息
        List<Item> items = itemService.list();
        List<ItemStock> stocks = stockService.list();
        //序列化为JSON并存入Redis
        for (Item item : items) {
            String itemJSON = MAPPER.writeValueAsString(item);
            redisTemplate.opsForValue().set("item:" + item.getId(), itemJSON);
        }
        for (ItemStock stock : stocks) {
            String itemJSON = MAPPER.writeValueAsString(stock);
            redisTemplate.opsForValue().set("item:stock:" + stock.getId(), itemJSON);
        }
    }

    /**
     * 保存Item
     * @param item
     */
    public void saveItem(Item item) {
        try {
            String json = MAPPER.writeValueAsString(item);
            redisTemplate.opsForValue().set("item:id:" + item.getId(), json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据id删除
     * @param id
     */
    public void deleteItemById(Long id) {
        redisTemplate.delete("item:id:" + id);
    }
}
